from cou.api_1_0 import api
from cou.models import taocan,Video
from cou.utils.Full_reduction import handle_data
import json
from cou import db
from cou.utils.catchdata import catchdata
from flask import jsonify,request,current_app
import subprocess
import os
import re
import time
@api.route('/saveData')
def saveData():
    filename=r"E:\hansen\python\Cou_le_me - 副本\cou\static\data2.8_panyu.json"
    with open(filename,encoding="utf8") as f:
        data=json.load(f)
    a=catchdata()
    value,merchant=a.full_reductiondata(data)
    try:
        for i in handle_data(value,merchant):
            t=taocan()
            t.name=i['name'],
            t.man=i['man']*100
            t.jian=i['jian']*100
            t.totalcost=i['totalcost']*100
            t.shopImgUrl=i['shopImgUrl']
            t.foods=json.dumps(i['food'])
            t.price=(i['totalcost']-i['jian'])*100
            t.rating=i['rating']*10
            t.areaId=1
            db.session.add(t)
        filename=r"E:\hansen\python\Cou_le_me - 副本\cou\static\data2.8_shipai.json"
        with open(filename,encoding="utf8") as f:
            data=json.load(f)
        a=catchdata()
        value,merchant=a.full_reductiondata(data)
        for i in handle_data(value,merchant):
            t=taocan()
            t.name=i['name'],
            t.man=i['man']*100
            t.jian=i['jian']*100
            t.totalcost=i['totalcost']*100
            t.shopImgUrl=i['shopImgUrl']
            t.foods=json.dumps(i['food'])
            t.price=(i['totalcost']-i['jian'])*100
            t.rating=i['rating']*10
            t.areaId=2
            db.session.add(t)
        db.session.commit()
        return jsonify({'message':"成功"})
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify({'message':"失败"})
def CutVideo(inputPath,begin,end,outputPath,fileName):
    #cmd="ffmpeg -ss {} -i {} -to {} -c copy -copyts {}".format(begin,inputPath,end,outputPath+fileName)
    try:
        outputPath=outputPath+str(time.time()).split('.')[0]+fileName
        cmd=r"ffmpeg -i {} -ss {} -c copy -to {} {} -y".format(inputPath+fileName,begin,end,outputPath)
        # cmd="dir"
        a=subprocess.Popen(cmd,shell=True)
        a.wait()
        return outputPath
    except Exception as e:
        raise e
@api.route("/cutVideo",methods=["POST"])
def cutVideo():
    file = request.files.get('video')
    begin=request.form.get('begin')
    end=request.form.get('end')
    #进行参数校验
    if not file:
        return jsonify({'errno':100,"errmsg":"视频文件不能为空"})
    if not begin:
        return jsonify({'errno':100,"errmsg":"起始时间不能为空"})
    if not end:
        return jsonify({'errno':100,"errmsg":"终止时间不能为空"})
    rex=r"([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$"#检验时间格式hh:mm:ss
    rex2=r"\d+$"#检验时间格式秒数
    if not re.match(rex,begin) and not re.match(rex2,begin):
        return jsonify({'errno':200,"errmsg":"起始时间格式错误"})
    if not re.match(rex,end) and not re.match(rex2,end):
        return jsonify({'errno':200,"errmsg":"终止时间格式错误"})
    #开始裁剪视频
    try:
        newVideo=Video()
        newVideo.user_id=1
        newVideo.status="裁剪中"
        db.session.add(newVideo)
        db.session.flush()
        savePath="./cou/static/upload/"
        with open(savePath+file.filename,"wb") as f:
            f.write(file.read())
        outPUtPath=CutVideo(savePath,begin,end,savePath,file.filename)
        #构建url
        print(outPUtPath)
        flag=os.path.exists(outPUtPath)
        if not flag:
            newVideo.status="视频裁剪失败"
            db.session.commit()
            return jsonify({'errno':300,"errmsg":"视频裁剪失败"})
        newVideo.video_path=outPUtPath[5:]
        newVideo.status="裁剪成功"
        db.session.commit()
        return jsonify({'message':"成功","errno":0,"data":newVideo.getVideoInfo()})
    except Exception as e:
        db.session.rollback()
        return jsonify({'message':str(e),"errno":400})
@api.route("/cutVideo/<int:id>")
def getCutVideo(id):
    a=Video.query.get(id)
    if not a:
        return jsonify({'message':"不存在该剪辑视频","errno":500})
    return jsonify({'message':"成功","errno":0,"data":a.getVideoInfo()})
    


